/**
 *
 * @description: 搜索组件
 * @author: junyong.hong
 * @createTime: 2019/8/10
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
import {HTTP} from '../util/http-p.js'

class KeywordModel extends HTTP{
    key = 'q'
    maxLength = 10

    // 获取历史数据
    getHistory () {
        const words = wx.getStorageSync(this.key)
        if (!words) {
            return []
        }

        return words
    }

    // 获取热门搜索
    getHot () {
        return this.request({
            url: '/book/hot_keyword'
        })
    }

    // 写入缓存
    addToHistory (keyword) {
        let words = this.getHistory()
        // 判断一个数组中是否包含keyword元素 includes:es6写法
        const has = words.includes(keyword)

        if (!has) {
            // 数组末尾删除，keyword数组第一位
            const length = words.length
            if (length >= this.maxLength) {
                words.pop()
            }

            // 可以添加到数组的首位
            words.unshift(keyword)
            wx.setStorageSync(this.key, words)
        }
    }
}

export {KeywordModel}